<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <title>请通过以下验证</title>
    <style>
        body {
            margin: 0;
        }

        .title {
            height: 18px;
            margin: 15px;
            font-size: 18px;
            line-height: 18px;
        }

        #log {
            display: none;
            margin: 0;
            word-break: break-all;
        }

        #log.log {
            display: block;
        }

        #captcha_index_loading {
            position: fixed;
            top: 50%;
            left: 50%;
            overflow: hidden;
            transform: translate(-50%, -50%);
        }

        #captcha {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 260px;
            height: 50px;
            transform: translate(-50%, -50%);
        }

        /* loading */
        .loader {
            width: 40px;
            height: 40px;
        }

        svg path,
        svg rect {
            fill: #3973ff;
        }
    </style>
</head>

<body>
    <div id="log"></div>
    <div id="captcha"></div>

    <div id="captcha_index_loading">
        <img class="captcha_index_img loader" id="captcha_img_loading" alt="加载中" style="display: none;">
    </div>
    <script>
        var debug = false;
        var logEle = document.getElementById('log');
        var isOffline = false;
        var indexVersion = '1.3.4'; // 中间页版本号，每次修改文件要进行版本号升级
        function log(str) {
            if (!debug) {
                return;
            }
            var p = document.createElement('p');
            p.appendChild(document.createTextNode(str));
            logEle.insertBefore(p, logEle.firstChild);
            // 同时将错误输出到控制台
            console.log(str);
        }
        (function () {
            // 错误构造函数
            function newError(msg, code, detail) {
                return {
                    desc: {
                        indexVersion: indexVersion,
                        detail: detail
                    },
                    msg: msg,
                    code: code
                }
            }
            function uploadExtraData(type, extraData) {
                var self = window;
                // 参数应该存在length属性，并且参数长度不可超过限制
                if (!extraData || (!extraData.length) || (extraData.length >= 1024 * 4)) {
                    return;
                }
                if (!self.extraData) {
                    self.extraData = {};
                }
                // 设计成可拓展的结构，防止以后有类似的字段增加需求
                self.extraData[type] = extraData;
            }
            var jsBridge = (function () {

                var callbacks = {
                    showBox: function () {
                        captchaObj.showBox &&  captchaObj.showBox();
                    },
                    postNativeMessage: function (data) {
                        log('getCore time: ' + ((new Date()).getTime()));
                        uploadExtraData('GeeToken', data);
                    }
                };
                var call = function (data) {
                    //调用原生方法
                    try {
                        nativeCall(JSON.stringify(data))
                    } catch (e) {
                        log('调用navtive接口异常');
                    }
                };
                // 适配鸿蒙
                var harmonys = JSON.parse(decodeURIComponent(location.href.split('?')[1].split('=')[1]));
                var nativeCall = harmonys.harmony?  function (data) {
                    if (window.webkit && window.webkit.messageHandlers) {
                        return window.webkit.messageHandlers.gt4Notify.postMessage.bind(window.webkit.messageHandlers.gt4Notify)
                    } else if (window.JSInterface) {
                        // return JSInterface.gt4Notify.bind(JSInterface)
                        JSInterface.call(data)
                    } else {
                        log('请在移动端环境运行')
                    }
                }: (function () {
                    if (window.webkit && window.webkit.messageHandlers) {
                        return window.webkit.messageHandlers.gt4Notify.postMessage.bind(window.webkit.messageHandlers.gt4Notify)
                    } else if (window.JSInterface) {
                        return JSInterface.gt4Notify.bind(JSInterface)
                    } else {
                        log('请在移动端环境运行')
                    }
                })();

                return {
                    callback: function (type, data) {
                        return callbacks[type](data);
                    },
                    callNative: call
                }
            })();
            // 暴露 jsBridge
            window.jsBridge = jsBridge;
            // jsBridge 与 全局错误捕获要尽可能早的加载，防止gt4中的错误捕获不到；
            if (window.addEventListener) {
                window.addEventListener('error', function (e) {
                    jsBridge.callNative({
                        type: 'error',
                        data: newError("gt4-index error", 60302, e.message)
                    });
                })
            } else {
                window.onerror = function (e) {
                    jsBridge.callNative({
                        type: 'error',
                        data: newError("gt4-index error", 60302, e.message)
                    });
                }
            }
        })();
    </script>

    <!-- 此链接位置不要改变，防止上面页面错误catch 不到gt4的错误-->
    <script src="./ct4.js"></script>

    <script>
        (function () {
            //geeToken兼容ai下无token
            if (!isOffline) {
                // 非宕机模式下获取移动端coreSDK数据
                jsBridge.callNative({
                    type: 'get'
                })
            }
            var startTime = 0;
            var clearID = 0;
            var captcha = document.getElementById('captcha');
            var loadingEle = document.getElementById('captcha_index_loading');
            var img = document.getElementById('captcha_img_loading');

            var query = location.href.split('?')[1];
            // 兼容安卓4.3版本样式问题
            var ua = navigator.userAgent.toLowerCase();
            if(/Android/.test(window.navigator.userAgent) && /android\s([\w.]+)/.exec(ua)[1] <= 4.3) {
                loadingEle.style.left = '45%';
            }
            
            // 兼容低版本Object.assign
            if (typeof Object.assign != 'function') {
                // Must be writable: true, enumerable: false, configurable: true
                Object.defineProperty(Object, "assign", {
                    value: function assign(target, varArgs) { // .length of function is 2
                    if (target == null) { // TypeError if undefined or null
                        throw new TypeError('Cannot convert undefined or null to object');
                    }

                    var to = Object(target);

                    for (var index = 1; index < arguments.length; index++) {
                        var nextSource = arguments[index];

                        if (nextSource != null) { // Skip over if undefined or null
                        for (var nextKey in nextSource) {
                            // Avoid bugs when hasOwnProperty is shadowed
                            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                            to[nextKey] = nextSource[nextKey];
                            }
                        }
                        }
                    }
                    return to;
                    },
                    writable: true,
                    configurable: true
                });
            }
            // 默认配置
            var config = {
                product: 'bind',
                onError: function (e) {
                    // 错误信息中插入版本号
                    e.desc = Object.assign({}, e.desc, { indexVersion: indexVersion });
                    jsBridge.callNative({
                        type: 'error',
                        data: e
                    });
                }
            };
            function setDebug() {
                debug = true;
                logEle.className = 'log';
            }
            
            function paseURI() {
                return JSON.parse(decodeURIComponent(query.split('=')[1]));
            }

            function checkArgs(args) {
                //设置loading
                if(args['loading']){
                  img.src = args['loading'];
                  clearID = setTimeout(function () {
                    img.style.display = 'inline-block';
                  }, 200);
                }
                // 是否开启debug
                if (args['debug']) {
                    setDebug(true);
                    startTime = (new Date()).getTime();
                    log(JSON.stringify(args))
                }

                // 设置title
                if (args['title'] && args['title'] != "") {
                    var h3 = document.createElement('h3');
                    h3.className = 'title';
                    h3.appendChild(document.createTextNode(decodeURIComponent(args['title'])));
                    captcha.appendChild(h3);
                }

                // 检查必要参数
                if (!args['captchaId']) {
                    log('args error: ' + query);
                }

                // 通过useLocalOffline判断是否会加入宕机效验
                if (args['useLocalOffline']) {
                    //宕机启用自己的方法
                    config.offlineCb = function () {

                        isOffline = true;

                        jsBridge.callNative({
                            type: 'result',
                            data: {
                                captcha_id: args['captchaId'],
                                challenge: args['challenge'],
                                offline: true
                            }
                        });
                    }
                }
            }

            function mergeOptions(args) {
                for (var k in args) {
                    if (args.hasOwnProperty(k) &&
                        ['debug', 'title',  args['type']].indexOf(k) === -1) {
                        config[k] = args[k];
                    }
                }
            }

            if (!query) {
                setDebug();
                log('no query: ' + location.href);
                return false;
            }

            // 解析参数
            var args = paseURI(query);

            // 检查参数
            checkArgs(args);

            // 合并配置项
            mergeOptions(args);

            // 初始化验证码
            var handler = function (captchaObj) {
                window.captchaObj = captchaObj;
                captchaObj
                    .appendTo(captcha)
                    .onSuccess(function () {
                        var result = captchaObj.getValidate();
                        log('Success validate: ' + result);
                        jsBridge.callNative({
                            type: 'result',
                            data: result
                        });

                    })
                    .onReady(function () {
                        log('load time: ' + ((new Date()).getTime() - (startTime || 0)));

                        jsBridge.callNative({
                            type: 'ready',
                            data: {
                                ready: 0
                            }
                        })

                        clearTimeout(clearID);
                        loadingEle.style.display = 'none';
                    })
                    .onClose(function () {
                        jsBridge.callNative({
                            type: 'close'
                        });
                    })
                    .onError(function (e) {
                        e.desc && (e.desc.indexVersion = indexVersion);
                        jsBridge.callNative({
                            type: 'error',
                            data: e
                        });
                    })
                    .onFail(function (e) {
                        jsBridge.callNative({
                            type: 'fail',
                            data: e
                        });
                    })
            };
            window.initAlicom4(config, handler);

        })();

    </script>
</body>

</html>